package com.hui.stock.utils;

import com.hui.stock.pojo.domain.MenuDomain;
import com.hui.stock.pojo.entity.SysPermission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: ymh
 * @date: 2024/12/30 17:14
 * @description:
 */
public class UserRolePermissionUtil {
    // 迭代方法来构建树状结构
    public static List<MenuDomain> buildPermissionTree(List<SysPermission> permissions) {
        // 将目录菜单列表放入map
        Map<Long, MenuDomain> menuMap = new HashMap<>();
        // 分类菜单和按钮权限
        permissions.forEach(permission->{
            if (permission.getType()!=3){
                MenuDomain menu = new MenuDomain();
                BeanUtils.copyProperties(permission, menu);
                menu.setPath(permission.getUrl());
                menu.setChildren(new ArrayList<>());
                menuMap.put(permission.getId(), menu);
            }
        });
        // 构建菜单层级结构
        Set<Long> rootMenuIds = new HashSet<>();
        permissions.forEach(permission -> {
            if (permission.getType() != 3 && permission.getPid() != 0) {
                MenuDomain parent = menuMap.get(permission.getPid());
                if (parent != null) {
                    parent.getChildren().add(menuMap.get(permission.getId()));
                }
            } else if (permission.getType() == 1) {
                rootMenuIds.add(permission.getId());
            }
        });
        return rootMenuIds.stream()
                .map(menuMap::get)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
